const fs = require('fs');
const config = require('../config/index');
const log4js = require('../config/log-config');
const logger = log4js.getLogger()//根据需要获取logger
const moment = require('moment');
const tokenModel = require('../model/token-model');


let obj = {
    /*
    * 设置成json的格式
    * code：返回数据的code码
    * message：返回的数据的信息
    * object：传入一个对象，也会将其合并到json格式中
    *
    * */
    setJsonStyle(code, message, data, ...arr) {
        const obj = {};
        obj.code = code;
        obj.message = message;
        obj.data = data;
        arr.forEach(item => {
            for (let key in item) {
                obj[key] = item[key];
            }
        })
        return JSON.stringify(obj);
    },

    //创建用户id和token
    createUserId() {
        let arr = [
            1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
        let str = '';
        for (let a = 0; a < 32; a++) {
            let num = Math.floor(Math.random() * arr.length);
            str += arr[num];
        }
        return str;
    },


    //删除指定文件夹对应的所有文件（递归删除）
    setTimeClearFile(path) {
        let timer;
        let handleTime = config.source.clearFileHeart;
        clearInterval(timer);
        timer = setInterval(() => {
            delelteFile();
        }, handleTime)
        let delelteFile = () => {
            let files = fs.readdirSync(path);
            if (!files.length) return;
            files.forEach((item) => {
                let currentPath = path + '/' + item;
                if (fs.statSync(currentPath).isDirectory()) { //是否为文件夹
                    delelteFile(currentPath)
                } else {
                    fs.unlinkSync(currentPath);
                    logger.warn('delete files success! ---' + currentPath);
                }
            })
        }
    },

    //手机验证
    validPhone(tel) {
        let patter = /^1[3|5|8|9]\d{9}$/;
        return patter.test(tel);
    },

    //时间格式化，默认 YYYY-MM-DD HH:mm:ss 格式
    dateFormat(timeStr, pattern = 'YYYY-MM-DD HH:mm:ss') {
        let formatDate = moment(timeStr).format(pattern);
        return formatDate;
    },

    //token验证是否失效
    tokenValid: async (req, res, cb) => {
        let token = req.headers.token || req.cookies.token;
        const tokenValidRes = await tokenModel.validToken(token);
        if (tokenValidRes && tokenValidRes !== 9999) {
            cb();
        } else if (tokenValidRes === 9999) {
            res.send(obj.setJsonStyle('9999', '系统异常'));
        } else {
            res.send(obj.setJsonStyle('1001', 'token失效'));
        }
    },

    /*
    * 验证码校验
    * telephone  手机号
    * code   验证码
    * */
    checkVerificationCode(telephone, code) {
        let defaultCode = '1234';  //先默认一个有效的验证码
        return new Promise((resolve, reject) => {
            if (code == defaultCode) {
                resolve(true);
            } else {
                resolve(false);
            }
        })
    },

    /*
    * 验证 mongooseObjectId 格式
    *
    * */
    checkObjectId(id) {
        let pat = /^[0-9a-fA-F]{24}$/;
        return pat.test(id);
    },



};

module.exports = obj;